package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    OrderMapper orderMapper;

    /**
     * 处理超时订单
     * 每分钟检查一次是否存在支付超时订单（下单后超过15分钟仍未支付则判定为支付超时订单）
     */
    @Scheduled(cron = "0 * * * * *") // 每分钟执行一次
    public void processTimeOutOrder() {

        LocalDateTime times = LocalDateTime.now().plusMinutes(-15);
        List<Orders> ordersList= orderMapper.getByStatusAndOrdertimeLT(Orders.PENDING_PAYMENT,times);
        if (ordersList.size()>0) {
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(LocalDateTime.now());
                orders.setCancelReason("订单超时，自动取消！");
                orderMapper.update(orders);

            }
        }
    }


    /**
     * 通过定时任务每天凌晨1点检查一次是否存在“派送中”的订单，如果存在则修改订单状态为“已完成”
     */
    @Scheduled(cron = "0 1 * * * *")
    public void processDeliveringOrder() {
        log.info("通过定时任务每天凌晨1点检查一次是否存在“派送中”的订单，如果存在则修改订单状态为“已完成");
        LocalDateTime localDateTime = LocalDateTime.now().plusHours(-1);
        List<Orders> byStatusAndOrdertimeLT = orderMapper.getByStatusAndOrdertimeLT(Orders.DELIVERY_IN_PROGRESS, localDateTime);
        if (byStatusAndOrdertimeLT.size()>0) {
            for (Orders orders : byStatusAndOrdertimeLT) {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);

            }
        }


    }





}
